﻿using Library.Common.Common;
using Library.Common.Model;
using Library.Common.Serialize;
using Library.Core.Application;
using Library.Core.Application.BaseAction;
using Library.Core.Application.IInfrastructure;
using Synthesize.BaseSet.Domain.Aggregation.Entity.Authority;
using Synthesize.BaseSet.Domain.Repository.Authority;
using Synthesize.BaseSet.ServiceInterface.Dtos.Authority.Post;
using Synthesize.BaseSet.ServiceInterface.UseCase.Authority;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Synthesize.BaseSet.Application.UseCase.Authority
{
    /// <summary>
    /// 岗位操作逻辑
    /// </summary>
    public class PostService : BaseService, IPostService
    {
        private readonly IPostRepository _postRepository;
        private readonly IUserPostRepository _userPostRepository;


        public PostService(IIocContainer container
            , IPostRepository postRepository
            , IUserPostRepository userPostRepository) : base(container)
        {
            _postRepository = postRepository;
            _userPostRepository = userPostRepository;
        }

        /// <summary>
        /// 创建岗位
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<BaseApiResult<bool>> Create(CreatePostInput input)
        {
            return await HandleAsync(input, async () =>
            {
                if (await _postRepository.AnyAsync(x => x.Name.Equals(input.Name)))
                {
                    throw new ApplicationsException("岗位名称重复！");
                }

                var post = MapperHelper<CreatePostInput, PostInfoEntity>.Map(input);
                post.Id = GuidHelper.GetSecuentialGuid();
                _postRepository.Add(post);

                return await _postRepository.SaveAsync();
            });
        }

        /// <summary>
        /// 禁用/启用岗位
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<BaseApiResult<bool>> ForbidOrEnable(ForbidOrEnableInput input)
        {
            return await HandleAsync(input, async () =>
            {
                var postInfo = await _postRepository.GetAsync(x => x.Id == input.Id);
                if (postInfo != null)
                {

                    postInfo.Status = !postInfo.Status;
                    _postRepository.Update(postInfo);
                }
                else
                {
                    throw new ApplicationsException("无对应岗位信息！");
                }
                return await _postRepository.SaveAsync();
            });
        }

        /// <summary>
        /// 更新岗位
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<BaseApiResult<bool>> Update(UpdatePostInput input)
        {

            return await HandleAsync(input, async () =>
            {
                var roleInfo = await _postRepository.GetAsync(x => x.Id == input.Id);
                if (roleInfo == null)
                {
                    throw new ApplicationsException("无对应岗位信息！");
                }
                if (await _postRepository.AnyAsync(x => x.Name.Equals(input.Name) && !x.Id.Equals(input.Id)))
                {
                    throw new ApplicationsException("岗位名称重复！");
                }
                roleInfo = MapperHelper<UpdatePostInput, PostInfoEntity>.Map(input);
                _postRepository.Update(roleInfo);

                return await _postRepository.SaveAsync();
            });
        }

        /// <summary>
        /// 更新岗位-用户信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<BaseApiResult<bool>> UpdatePostUser(UpdatePostUserInput input) {

            return await HandleAsync(input, async () =>
            {

                var userPostList = await _userPostRepository.GetManyAsync(x => input.PostId.Equals(x.PostId));
                if (userPostList.Any())
                {
                    _userPostRepository.UpdateIsDeletedRange(userPostList);
                }

                var addUserPosts = new List<UserPostReEntity>();
                if (input.UserIdList.Any())
                {
                    foreach (var item in input.UserIdList)
                    {
                        addUserPosts.Add(new UserPostReEntity()
                        {
                            Id = GuidHelper.GetSecuentialGuid(),
                            PostId = input.PostId,
                            UserId = item
                        });
                    }
                    await _userPostRepository.AddRangeAsync(addUserPosts);
                }
                return await _userPostRepository.SaveAsync();
            });
        }

        /// <summary>
        /// 删除岗位
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<BaseApiResult<bool>> DeleteById(SingleDeleteInput input)
        {

            return await HandleAsync(input, async () =>
            {
                var post = await _postRepository.GetAsync(input.Id);
                if (post == null)
                {
                    throw new ApplicationsException("无对应岗位信息存在！");
                }
                _postRepository.UpdateIsDeleted(post);

                var userPosts = await _userPostRepository.GetManyAsync(x=>x.PostId== input.Id);
                if (userPosts.Any())
                {
                    foreach (var userPost in userPosts)
                    {
                        _userPostRepository.Delete(userPost);
                    }
                }

                return await _postRepository.SaveAsync();

            });
        }

        /// <summary>
        /// 删除指定的用户-岗位关系
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<BaseApiResult<bool>> DeleteUserPost(DeleteUserPostInput input)
        {
            return await HandleAsync(input, async () =>
            {
                var userPost = await _userPostRepository.GetAsync(x => input.PostId.Equals(x.PostId) && input.UserId.Equals(x.UserId));
                if (userPost != null)
                {
                    _userPostRepository.UpdateIsDeleted(userPost);
                }
                return await _userPostRepository.SaveAsync();
            });
        }
    }
}
